﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web;
using System.Collections.Specialized;

using System.Reflection;

namespace lxwmvc
{
    /// <summary>
    /// 功能:处理Request请求，包括从request捕获数据等基础函数
    /// [09.4.10 lxw]<para />
    /// </summary>
    public class requesthelper 
    {
        /// <summary>
        /// 功能:获取前一个页面的Url地址
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <returns>返回Url地址字符串</returns>
        public static string formurl()
        {
            NameValueCollection coll = HttpContext.Current.Request.ServerVariables;
            var o = getonevalue("furl");
            //这里还是存在问题。formurl
            if (string.IsNullOrEmpty(o))
            {
                string url = coll["HTTP_REFERER"];
                if (string.IsNullOrEmpty(url)) return "";
                return url;
                //string pre = "";
                //string k = "";

                //if (url.IndexOf('?') == -1)
                //{
                //    pre = url;
                //}
                //else
                //{
                //    k = url.Substring(url.IndexOf('?') + 1);
                //    pre = url.Substring(0, url.IndexOf('?'));
                //}

                //Dictionary<string, string> di = new Dictionary<string, string>();
                //{
                //    if (k.Trim() != "")
                //    {
                //        string[] ks = k.Split(new char[] { '=', '&' });
                //        for (int i = 0; i < ks.Length / 2; i++)
                //            di[ks[i * 2]] = ks[i * 2 + 1];
                //    }
                //}
                //{
                //    k = HttpContext.Current.Request.QueryString.ToString();
                //    if (k.Trim() != "")
                //    {
                //        string[] ks = k.Split(new char[] { '=', '&' });
                //        for (int i = 0; i < ks.Length / 2; i++)
                //            di[ks[i * 2]] = ks[i * 2 + 1];
                //    }
                //}

                //di.Remove("_controller_");
                //di.Remove("_table_");
                //di.Remove("_pk_");
                //di.Remove("_action_");

                //StringBuilder sb = new StringBuilder();
                //sb.Append("1=1");
                //foreach (var o1 in di)
                //{
                //    sb.Append("&");
                //    sb.Append(o1.Key + "=" + o1.Value);
                //}
                ////返回数据
                //return pre + "?" + sb.ToString();
            }
            else
                return o.tostr();
        }

        /// <summary>
        /// 获取传递过来的值，如果不存在，就用""字符串代替
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string getonevalue(string key)
        {
            string v = "";
            HttpRequest Request = HttpContext.Current.Request;
            if (Request.HttpMethod == "POST")
            {
                //如果查询，直接定位到第一页。
                if (key.ToLower() == "page") return "0";
                v = Request.Form[key];
                if (v == null) v = Request.QueryString[key];
            }
            else
            {
                v = Request.QueryString[key];
            }

            return v;
        }

        /// <summary>
        /// 功能:从url里面的参数中得到对应键的值
        /// [11-03-08 16:02  周二 lxw]<para />
        /// </summary>
        /// <param name="strUrlParams">需要检索的字符串</param>
        /// <param name="strKey">需要找的键</param>
        /// <param name="split">默认分割的字符串</param>
        /// <returns>返回对应键的值</returns>
        public static string fromurlparamsgetvaluebykey(string strUrlParams, string strKey, string split="=")
        {
            int pos = 0;
            int end = 0;

            if ((pos = strUrlParams.ToLower().IndexOf(strKey.ToLower() + split)) != -1)
            {
                end = strUrlParams.ToLower().IndexOf("&", pos);
                if (end == -1) return strUrlParams.Substring(pos + strKey.Length + 1);
     
                if (end - (pos + strKey.Length + 1) == 0) return "";
                
                return strUrlParams.Substring(pos + strKey.Length + 1, end - (pos + strKey.Length + 1));
            }

            return "";
        }

        /// <summary>
        /// 功能:获取客户端IP地址,这个ip地址是可以被模拟的，所以，不起多大作用。
        /// [09.4.12 lxw]<para />
        /// </summary>
        /// <returns>返回客户端IP地址字符串</returns>
        public static string clientip()
        {
            string strIPAddr = "127.0.0.1";

            try
            {
                HttpRequest Request = HttpContext.Current.Request;
#if DEBUG

                if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == ""
                    || stringhelper.instr(Request.ServerVariables["HTTP_X_FORWARDED_FOR"], "unknown") > 0
                    )
                {
                    strIPAddr = Request.ServerVariables["REMOTE_ADDR"];
                }
                else if (Request.ServerVariables["REMOTE_ADDR"] != null)
                {
                    strIPAddr = Request.ServerVariables["REMOTE_ADDR"];
                }
                else if (stringhelper.instr(Request.ServerVariables["HTTP_X_FORWARDED_FOR"], ",") > 0)
                {
                    strIPAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                }
                else if (stringhelper.instr(Request.ServerVariables["HTTP_X_FORWARDED_FOR"], ";") > 0)
                {
                    strIPAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                }
                else
                {
                    strIPAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                }

#else

                strIPAddr = Request.ServerVariables["HTTP_ALI_CDN_REAL_IP"];

#endif

                return strIPAddr.tostr().Split(new char[] { ',', ';' })[0];
            }
            catch
            {
                return strIPAddr;
            }
        }


       // //TODO: 给实体赋值 于坤
       ///// <summary>
       ///// 给实体赋值 通过Request 给实体赋值
       ///// 调用方法例如：FlowType flowType = new FlowType(); RequestHelper.SetObjectPropertyValue(flowType, Request);
       ///// </summary>
       ///// <param name="obj">要赋值的实体</param>
       ///// <param name="request">Request对象</param>
       // public static void SetObjectPropertyValue(object obj, IRequest request)
       // {
       //     PropertyInfo[] pros = obj.GetType().GetProperties();
       //     foreach (PropertyInfo pi in pros)
       //     {
       //         if (pi.PropertyType == typeof(Int32))
       //             pi.SetValue(obj, ConvertHelper.Int(request.Params[pi.Name]).IntResult, null);
       //         else if (pi.PropertyType == typeof(string))
       //             pi.SetValue(obj, ConvertHelper.String(request.Params[pi.Name]).StringResult, null);
       //         else if (pi.PropertyType == typeof(DateTime))
       //             pi.SetValue(obj, ConvertHelper.DateTime(request.Params[pi.Name]).DateTimeResult, null);
       //         else if (pi.PropertyType == typeof(Decimal))
       //             pi.SetValue(obj, ConvertHelper.Decimal(request.Params[pi.Name]).DecimalResult, null);
       //     }
       // }
    }
}
